﻿using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        public static partial class ToolTips
        {
            public const string RemoveBone = "Removes bone(s) from bone-weights and boneArray" +
            "BoneWieghts fall back to other weighted bones or the closest root bone.";
        }

        [CtxMenuItem("SkinnedMeshRenderer/Bones/Remove Bone", ToolTips.RemoveBone, ContextFlag.Bone, 0)]
        public static void SkinnedMeshRendererRemoveBone()
        {
            GameObject boneContext = SkinnEx.FindGameObject(SkinnContext.ContextBone0);
            var items = SkinnContext.GetContextItems();
            foreach (var item in items)
            {
                var context = item.GetComponent<SkinnedMeshRenderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                SkinnedMeshRenderer newAsset;
                SkinnEx.CloneRemoveBones(context, new Transform[] { boneContext.transform }, out newAsset);
                if (newAsset)
                {
                    Undo.RegisterCompleteObjectUndo(context, "Remove Bone" + boneContext.name);

                    context.sharedMesh = newAsset.sharedMesh;
                    context.rootBone = newAsset.rootBone;
                    context.bones = newAsset.bones;
                    context.SetBounds();
                    SkinnEx.Release(newAsset.gameObject);
                }
            }
            SkinnContext.Finished();
        }

        [CtxMenuItem("SkinnedMeshRenderer/Bones/Remove Child Bones", ToolTips.RemoveBone, ContextFlag.BoneWithChildern, 0)]
        public static void SkinnedMeshRendererRemoveChildBones()
        {
            GameObject boneContext = SkinnEx.FindGameObject(SkinnContext.ContextBone0);
            var items = SkinnContext.GetContextItems();
            foreach (var item in items)
            {
                var context = item.GetComponent<SkinnedMeshRenderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                var childern = boneContext.transform.GetAllChildren().ToArray();
                SkinnedMeshRenderer newAsset;
                SkinnEx.CloneRemoveBones(context, childern, boneContext.transform, out newAsset);
                if (newAsset)
                {
                    Undo.RegisterCompleteObjectUndo(context, "Remove Bones");

                    context.sharedMesh = newAsset.sharedMesh;
                    context.rootBone = newAsset.rootBone;
                    context.bones = newAsset.bones;
                    context.SetBounds();
                    SkinnEx.Release(newAsset.gameObject);
                }
            }
            SkinnContext.Finished();
        }
    }
}